<template>
  <div class="app-container">
    <div class="user-profile">
      <div class="box-center">
        <pan-thumb :image="user.avatar">
          <i class="el-icon-camera-solid" style="color: grey; cursor: pointer" @click="imagecropperShow=true"/>
        </pan-thumb>
      </div>

      <div class="box-center">
        <div class="user-name text-center">{{ user.nickName }}</div>
      </div>

      <el-divider/>

      <el-descriptions :column="3" class="margin-top" title="基本信息" border>
        <template slot="extra">
          <el-button v-if="editInfo === false" type="primary" size="mini" plain @click="editInfo = true">编辑</el-button>
          <el-form v-else>
            <el-form-item>
              <el-button :disabled="saveInfoBtn" type="primary" size="mini" plain @click="updateInfo">保存</el-button>
            </el-form-item>
          </el-form>
        </template>
        <el-descriptions-item v-if="editInfo === false">
          <template slot="label">
            用户名
          </template>
          {{ user.username }}
        </el-descriptions-item>
        <el-descriptions-item v-if="editInfo === false">
          <template slot="label">
            昵称
          </template>
          {{ user.nickName }}
        </el-descriptions-item>
        <el-descriptions-item v-if="editInfo === false">
          <template slot="label">
            姓名
          </template>
          {{ user.name }}
        </el-descriptions-item>
        <el-descriptions-item v-if="editInfo === false">
          <template slot="label">
            性别
          </template>
          {{ user.gender === 0 ? '女' : '男' }}
        </el-descriptions-item>
        <el-descriptions-item v-if="editInfo === false">
          <template slot="label">
            个人简介
          </template>
          {{ user.signature }}
        </el-descriptions-item>
      </el-descriptions>

      <el-form v-if="editInfo" ref="user" :model="user" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="user.username" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input v-model="user.nickName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              :rules="[
                { required: false },
                { validator: nameRule, trigger: 'blur' }
              ]"
              prop="name"
              label="姓名">
              <el-input v-model="user.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="user.gender">
                <el-radio :label="0">女</el-radio>
                <el-radio :label="1">男</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="个人简介">
              <el-input
                v-model="user.signature"
                :autosize="{ minRows: 2, maxRows: 5}"
                type="textarea"
                maxlength="100"
                show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <br><br>

      <el-descriptions :column="3" :colon="false" class="margin-top" title="兴趣标签">
        <template slot="extra">
          <el-button v-if="editInterest" :disabled="saveInterestBtn" type="primary" size="mini" plain @click="saveInterests">保存</el-button>
          <el-form v-else>
            <el-button type="primary" size="mini" plain @click="editInterest = true">编辑</el-button>
          </el-form>
        </template>
        <el-descriptions-item v-if="editInterest === false">
          <el-tag
            v-for="interest in user.interests"
            :key="interest.id"
            size="small">
            {{ interest.name }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <div v-if="editInterest">
        <el-tag
          v-for="interest in user.interests"
          :key="interest.id"
          size="small"
          closable
          @close="handleClose(interest.id)">
          {{ interest.name }}
        </el-tag>
        <el-cascader-panel
          ref="interestCascader"
          v-model="checkInterests"
          :options="options"
          :props="{ multiple: true, checkStrictly: true, emitPath: false }"
          @change="handleChange"/>
      </div>

      <br><br>

      <el-descriptions :column="1" :colon="false" class="margin-top" title="账号设置">
        <el-descriptions-item/>
      </el-descriptions>

      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="4">
          密&nbsp;&nbsp;&nbsp;&nbsp;码
        </el-col>
        <el-col :span="6" :offset="10">
          * * * * * * * * * * * *
        </el-col>
        <el-col :span="4">
          <el-button type="text" size="medium" style="padding-top: 0" @click="gotoPassword">修改密码</el-button>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="4">
          邮&nbsp;&nbsp;&nbsp;&nbsp;箱
        </el-col>
        <el-col :span="6" :offset="10">
          {{ encryptEmail }}
        </el-col>
        <el-col :span="4">
          <el-button v-if="user.email === ''" type="text" size="medium" style="padding-top: 0" @click="gotoEmail">绑定邮箱
          </el-button>
          <el-button v-else type="text" size="medium" style="padding-top: 0" @click="gotoEmail">
            修改邮箱
          </el-button>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="4">
          手&nbsp;&nbsp;&nbsp;&nbsp;机
        </el-col>
        <el-col :span="6" :offset="10">
          {{ encryptPhone }}
        </el-col>
        <el-col :span="4">
          <el-button v-if="user.phone === ''" type="text" size="medium" style="padding-top: 0" @click="gotoPhone">绑定手机</el-button>
          <el-button v-else type="text" size="medium" style="padding-top: 0" @click="gotoPhone">修改手机</el-button>
        </el-col>
      </el-row>

      <br><br>

    </div>

    <image-cropper
      v-show="imagecropperShow"
      :key="imagecropperKey"
      :width="150"
      :height="150"
      lang-type="zh"
      @close="close"
      @crop-upload-success="cropSuccess"/>
  </div>
</template>

<script>
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'

import userApi from '@/api/ucenter/user'
import interestApi from '@/api/ucenter/interest'

export default {
  name: 'Profile',

  components: { ImageCropper, PanThumb },

  data() {
    return {
      imagecropperShow: false,
      imagecropperKey: 0,
      editInfo: false,
      editInterest: false,
      saveInfoBtn: false,
      saveInterestBtn: false,
      user: {
        id: '',
        username: '',
        nickName: '',
        name: '',
        gender: '',
        phone: '',
        email: '',
        avatar: '',
        signature: '',
        interests: []
      },
      checkInterests: [],
      options: []
    }
  },

  computed: {

    encryptEmail() {
      if (this.user.email === '') {
        return '未绑定'
      } else {
        return this.user.email.substr(0, 3) + ' * * * ' + this.user.email.substr(this.user.email.indexOf('@'))
      }
    },

    encryptPhone() {
      if (this.user.phone === '') {
        return '未绑定'
      } else {
        return this.user.phone.substr(0, 3) + ' * * * * ' + this.user.phone.substr(7)
      }
    }

  },

  created() {
    this.getCurrentUserInfo()
    this.getAllInterests()
  },

  methods: {

    getCurrentUserInfo() {
      userApi.getCurrentUserInfo().then(res => {
        this.user = res.result
        this.checkInterests = this.user.interests.map(interest => interest.id)
      }).catch(error => {
        console.log(error)
      })
    },

    getAllInterests() {
      interestApi.getAllInterests().then(res => {
        this.options = res.result
      }).catch(error => {
        console.log(error)
      })
    },

    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.user.avatar = resData
      this.$message({
        type: 'success',
        message: '头像上传成功'
      })
      this.$store.commit('SET_AVATAR', this.user.avatar)
      userApi.updateAvatar(this.user.avatar).then(res => {
        this.$message({
          type: 'success',
          message: res.result
        })
      }).catch(error => {
        console.log(error)
      })
    },

    close() {
      this.imagecropperShow = false
    },

    nameRule(rule, value, callback) {
      if (!/^([\u4E00-\u9FA5])*$/.test(value)) {
        callback(new Error('真实姓名应只包含中文'))
      }
      callback()
    },

    updateInfo() {
      this.$refs['user'].validate(valid => {
        if (valid) {
          this.saveInfoBtn = true
          userApi.updateInfo(this.user).then(res => {
            this.$message({
              type: 'success',
              message: res.result
            })
            this.editInfo = false
            this.saveInfoBtn = false
          }).catch(error => {
            this.saveInfoBtn = false
            console.log(error)
          })
        }
      })
    },

    handleChange(val) {
      this.user.interests = []
      this.$refs['interestCascader'].getCheckedNodes().forEach(({
        value,
        label
      }) => this.user.interests.push({ id: value, name: label }))
    },

    handleClose(id) {
      this.checkInterests = this.checkInterests.filter(checkId => checkId !== id)
      this.user.interests = this.user.interests.filter(interest => interest.id !== id)
    },

    saveInterests() {
      this.saveInterestBtn = true
      interestApi.updateInterests(this.user.interests.map(interest => interest.id)).then(res => {
        this.$message({
          type: 'success',
          message: res.result
        })
        this.editInterest = false
        this.saveInterestBtn = false
      }).catch(error => {
        this.saveInterestBtn = false
        console.log(error)
      })
    },

    gotoPassword() {
      this.$router.push({ name: '密码设置', params: { email: this.user.email, phone: this.user.phone }})
    },

    gotoEmail() {
      this.$router.push({ name: '邮箱设置', params: { email: this.user.email }})
    },

    gotoPhone() {
      this.$router.push({ name: '手机设置', params: { phone: this.user.phone }})
    }

  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}

.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
}

.user-profile {
  width: 60%;
  margin: auto;
  border: grey solid;
  padding: 15px;

  .user-name {
    font-weight: bold;
    font-size: x-large;
  }

  .box-center {
    padding-top: 10px;
  }

  .user-role {
    padding-top: 10px;
    font-weight: 400;
    font-size: 14px;
  }

  .box-social {
    padding-top: 30px;

    .el-table {
      border-top: 1px solid #dfe6ec;
    }
  }

  .user-follow {
    padding-top: 20px;
  }
}

.user-bio {
  margin-top: 20px;
  color: #606266;

  span {
    padding-left: 4px;
  }

  .user-bio-section {
    font-size: 14px;
    padding: 15px 0;

    .user-bio-section-header {
      border-bottom: 1px solid #dfe6ec;
      padding-bottom: 10px;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
}
</style>
